package geekstudy.week4;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 *
 * https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
 * 701. 二叉搜索树中的插入操作
 *
 *
 * 执行结果：  通过    显示详情
 *
 * 添加备注
 * 执行用时：0 ms, 在所有 Java 提交中击败了100.00% 的用户
 * 内存消耗：39.2 MB, 在所有 Java 提交中击败了21.64% 的用户
 *
 */
public class Week4InsertIntoABinarySearchTree {

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) {
            return new TreeNode(val);
        }

        if(root.val < val) {
            root.right = insertIntoBST(root.right, val);
        } else {
            root.left = insertIntoBST(root.left, val);
        }
        return root;

    }

    public List<Integer> preorder(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        if(root != null) {
            list.add(root.val);

            List<Integer> leftList = preorder(root.left);
            list.addAll(leftList);

            List<Integer> rightList = preorder(root.right);
            list.addAll(rightList);
        }
        return list;
    }

    public List<Integer> levelOrder(TreeNode root) {
        List<Integer> levelList = new ArrayList<Integer>();
        if(root != null) {
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            queue.offer(root);
            for(;!queue.isEmpty();) {
                int size = queue.size();
                ArrayList<Integer> list = new ArrayList<Integer>();
                for(int i = 0; i < size; i++)  {
                    TreeNode node = queue.poll();
                    list.add(node.val);
                    if(node.left != null) {
                        queue.offer(node.left);
                    }
                    if(node.right != null) {
                        queue.offer(node.right);
                    }
                }
                levelList.addAll(list);
            }
        }

        return levelList;
    }


}
